﻿using System.Collections.Concurrent;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace PMIS.Controls
{
    public partial class ToastWindow : Window
    {
        public ToastWindow(string message)
        {
            InitializeComponent();
            MessageTextBlock.Text = message;

            Storyboard fadeInOut = new Storyboard();

            DoubleAnimation fadeIn = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(0.5)));
            Storyboard.SetTargetName(fadeIn, "toastBorder");
            Storyboard.SetTargetProperty(fadeIn, new PropertyPath(Border.OpacityProperty));
            fadeInOut.Children.Add(fadeIn);

            DoubleAnimation fadeOut = new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromSeconds(0.5)))
            {
                BeginTime = TimeSpan.FromSeconds(2.5)
            };
            Storyboard.SetTargetName(fadeOut, "toastBorder");
            Storyboard.SetTargetProperty(fadeOut, new PropertyPath(Border.OpacityProperty));
            fadeInOut.Children.Add(fadeOut);

            fadeInOut.Completed += (s, e) => this.Close();
            this.Resources.Add("FadeInOut", fadeInOut);
            fadeInOut.Begin(this);
        }

        ~ToastWindow()
        {
            Debug.WriteLine("~ToastWindow");
        }
    }

    public class ToastManager
    {
        private static readonly Lazy<ToastManager> instance = new Lazy<ToastManager>(() => new ToastManager());

        private readonly ConcurrentQueue<string> messageQueue;
        private bool isDisplaying;

        private ToastManager()
        {
            messageQueue = new ConcurrentQueue<string>();
            isDisplaying = false;
        }

        public static ToastManager Instance => instance.Value;

        public void Show(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }
            messageQueue.Enqueue(message);
            if (!isDisplaying)
            {
                DisplayNextToast();
            }
        }

        private async void DisplayNextToast()
        {
            isDisplaying = true;

            if (messageQueue.TryDequeue(out string message))
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    ToastWindow toast = new ToastWindow(message);
                    toast.Show();
                });

                await Task.Delay(3500); // 等待 3 秒 + 动画时间
                DisplayNextToast();
            }
            else
            {
                isDisplaying = false;
            }
        }

        public static void ShowToast(string message)
        {
            ToastManager.Instance.Show(message);
        }
    }
}
